<!-- 修改弹窗 -->
<template>
  <div>
    <el-dialog
      :model-value="visible"
      title="商品修改"
      style="border-radius: 10px"
      @close="cls"
    >
      <el-form :inline="true" class="update-form">
        <!-- 左侧表单 -->
        <div class="form-left">
          <el-form-item label="商品名称:" class="myFormItem" size="large">
            <el-input v-model="data.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="商品价格:" size="large" class="myFormItem">
            <el-input v-model="data.price" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="商品颜色:" class="myFormItem" size="large">
            <el-input v-model="data.color" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="商品材质:" class="myFormItem" size="large">
            <el-input v-model="data.material" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="商品样式:" class="myFormItem" size="large">
            <el-input v-model="data.style" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="商品重量:" class="myFormItem" size="large">
            <el-input v-model="data.specifications" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="商品数量:" class="myFormItem" size="large">
            <el-input-number v-model="data.num" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="商品分类:" size="large" class="myFormItem">
            <el-tree-select
              v-model="data.className"
              :data="classTree"
              style="width: 200px"
              :props="{
                children: 'children',
                label: 'name',
                value: 'id'
              }"
            />
          </el-form-item>
        </div>

        <!-- 右侧图片上传 -->
        <div class="form-right">
          <el-form-item label="商品主图:" class="myFormItem" size="large">
            <div class="image-preview">
              <el-image
                :src="data.picture"
                class="myImage"
                :preview-src-list="[data.picture]"
                :initial-index="0"
                fit="cover"
              />
              <el-upload
                v-model:file-list="fileList"
                :on-success="fUpload"
                action="http://localhost:2000/api/minio/uploadImages"
                :show-file-list="false"
              >
                <el-button type="primary" size="default">点击替换</el-button>
              </el-upload>
            </div>
          </el-form-item>

          <el-form-item label="商品详情图" class="myFormItem">
            <div class="image-list">
              <el-upload
                v-model:file-list="data.detailImageList"
                action="http://localhost:2000/api/minio/uploadImages"
                list-type="picture-card"
                :on-success="detailSuccess"
                :before-remove="bremove"
                :on-preview="handlePreview"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </div>
          </el-form-item>

          <el-form-item label="商品轮播图:" class="myFormItem">
            <div class="image-list">
              <el-upload
                v-model:file-list="data.carouselList"
                action="http://localhost:2000/api/minio/uploadImages"
                list-type="picture-card"
                :on-success="carousel"
                :before-remove="bremoveCarousel"
                :on-preview="handlePreview"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </div>
          </el-form-item>
        </div>
      </el-form>

      <!-- 底部按钮 -->
      <div class="dialog-footer">
        <el-button @click="cls">取消</el-button>
        <el-button type="primary" @click="mySubmmit">确认修改</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="预览">
      <img :src="previewUrl" alt="Preview Image" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineProps } from "vue";
import { getClassTree, Pupdate } from "../../api/product/product.js";
import { Plus } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";

//声明对象用于接收数据
const data = ref({});
//声明事件
const emits = defineEmits(["close"]);
// 定义属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});
//分类树
const classTree = ref();
const fileList = ref([]);
//主图上传
function fUpload() {
  //获取数组的最后一个元素
  let a = fileList.value.at(-1);
  // 重新赋值给当前data
  data.value.picture = a.response.data;
}

//商品详情删除前的方法
async function bremove(uploadFile) {
  try {
    await ElMessageBox.confirm("确定要删除吗?");
    // 使用 filter 方法过滤掉要删除的图片
    data.value.detailImageList = data.value.detailImageList.filter(
      item => item.url !== uploadFile.url
    );
    return true;
  } catch {
    return false;
  }
}
//商品轮播删除
async function bremoveCarousel(uploadFile) {
  try {
    await ElMessageBox.confirm("确定要删除吗?");
    // 使用 filter 方法过滤掉要删除的图片
    data.value.carouselList = data.value.carouselList.filter(
      item => item.url !== uploadFile.url
    );
    return true;
  } catch {
    return false;
  }
}
//详情上传
function detailSuccess(response) {
  if (response.code === 200) {
    data.value.detailImageList.at(-1).product_id = data.value.id;
    data.value.detailImageList.at(-1).url = response.data;
  }
}
//轮播上传
function carousel(response) {
  if (response.code === 200) {
    data.value.carouselList.at(-1).product_id = data.value.id;
    data.value.carouselList.at(-1).url = response.data;
  }
}
//提交
async function mySubmmit() {
  let cList = [];
  // 在组件加载时，把后端返回的文件列表处理为 el-upload 可识别的格式
  cList = data.value.carouselList.map(file => ({
    carousel: file.url, // 映射为 url
    id: file.id,
    product_id: file.product_id
  }));
  data.value.carouselList = cList;
  // 在组件加载时，把后端返回的文件列表处理为 el-upload 可识别的格式
  let dList = [];
  dList = data.value.detailImageList.map(file => ({
    product_detail_image: file.url, // 映射为 url
    id: file.id,
    product_id: file.product_id
  }));
  data.value.detailImageList = dList;

  let res = await Pupdate(data.value);
  if (res.code == 200) {
    ElMessage({
      message: "修改成功!",
      type: "success"
    });
  }
  cls();
}
// 关闭方法
function cls() {
  // 通知父组件关闭
  emits("close");
}
//初始化方法
function init(i) {
  //赋值给data对象
  console.log(i);
  data.value = i;
  //获取部门树内容
  let res = getClassTree();
  res.then(response => {
    classTree.value = response.data;
  });
}
// 暴露初始化方法
defineExpose({ init });

// 预览相关的响应式变量
const previewVisible = ref(false);
const previewUrl = ref("");

// 处理图片预览
const handlePreview = file => {
  previewUrl.value = file.url || file.response?.data;
  previewVisible.value = true;
};
</script>

<style scoped>
.update-form {
  display: flex;
  gap: 20px;
}

.form-left {
  flex: 1;
}

.form-right {
  flex: 1;
}

.myFormItem {
  margin-bottom: 20px;
  width: 100%;
}

.image-preview {
  display: flex;
  align-items: center;
  gap: 12px;
}

.myImage {
  width: 100px;
  height: 100px;
  border-radius: 10px;
  cursor: pointer;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  line-height: 100px;
  border-radius: 10px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

:deep(.el-upload-list--picture-card .el-upload-list__item:hover) {
  transform: scale(1.05);
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 预览对话框样式 */
:deep(.el-dialog__body) {
  text-align: center;
  padding: 20px;
}
</style>
